package com.chiyi.transaction;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chiyi.bean.TLog;
import com.chiyi.bean.TOrder;
import com.chiyi.mapper.TLogMapper;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.messaging.Message;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * @date 2021/5/15 14:01
 * 事务监听类
 */
@RocketMQTransactionListener(txProducerGroup = "tx_producer_group")
public class OrderTransactionListener implements RocketMQLocalTransactionListener {

    @Resource
    private OrderServiceTrans orderServiceTrans;
    @Resource
    private TLogMapper tLogMapper;


    // 本地事务
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
        try {
            // 提交订单
            orderServiceTrans.createOrder(Objects.requireNonNull(message.getHeaders().get("txid")).toString(), (TOrder) o);
            return RocketMQLocalTransactionState.COMMIT;
        } catch (Exception e) {
            // 回滚
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }

    // 消息回查
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        QueryWrapper qw = new QueryWrapper();
        qw.eq("tx_id", Objects.requireNonNull(message.getHeaders().get("txid")).toString());
        TLog log = tLogMapper.selectOne(qw);
        // 判断
        if (log == null) {
            return RocketMQLocalTransactionState.COMMIT;
        } else {
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }
}
